import { Component } from 'react'
import Taro from '@tarojs/taro'
import {View, Text, Textarea} from '@tarojs/components'
import './index.scss'
import global from '../../global';
import { Button, Map, Swiper, SwiperItem, Picker, Input, Image } from '@tarojs/components'
import Request from '../../api/index'
import Utils from '../../utils'
import Event from '../../event';

export default class Index extends Component {

  constructor() {
    super();
    this.state = {
      form: {
        realName: '',
        idCard: '',
        regionId: '',
        regionName: '',
        villageId: '',
        villageName: '',
        buildingId: '',
        buildingName: '',
        unitId: '',
        unitName: '',
        houseId: '',
        houseName: ''
      },
      loading: false,
      editable: true,
      isApply: false
    }
    this.submitForm = this.submitForm.bind(this)
    this.checkApplyStatus = this.checkApplyStatus.bind(this);
    this.updateRemindStatus = this.updateRemindStatus.bind(this);
    this.applyJob = this.applyJob.bind(this);
  }

  componentWillMount () {
    if (global.isApplyJob) {
      this.checkApplyStatus()
      this.setState({
        form: global.currentApplyJob,
        editable: false
      })
      this.updateRemindStatus();
    }
  }

  componentDidMount () {
  }

  componentWillUnmount () {
  }

  componentDidShow () { }

  componentDidHide () { }

  async updateRemindStatus() {
    try {
      let res = await Request.get(`/business/operation_remind/updateStatus/${global.currentApplyJob.jobId}/JOB/${global.userInfo.userId}`);
      if (res.data.code !== 200) {
        throw new Error();
      }
      console.log(res.data.data)
    } catch (e) {
      console.log("更新状态异常")
    }
  }

  validateForm(form) {

    if (!form.name) {
      Taro.showToast({
        title: '请输入岗位名称！',
        icon: "error",
        duration: 1000
      });
      return false;
    }
    if (!form.phone) {
      Taro.showToast({
        title: '请输入联系方式！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.salary) {
      Taro.showToast({
        title: '请输入薪资待遇！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.salary) {
      Taro.showToast({
        title: '请输入薪资待遇！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.education) {
      Taro.showToast({
        title: '请输入学历要求！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.experience) {
      Taro.showToast({
        title: '请输入经验要求！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.des) {
      Taro.showToast({
        title: '请输入职位描述！',
        icon: "error",
        duration: 1000
      })
      return false;
    }

    return true;
  }

  async applyJob() {
    if (this.state.loading) {
      return;
    }
    this.state.loading = true;
    this.setState({
      loading: true
    })
    let form = {}
    form.userId = global.userInfo.userId;
    form.jobId = global.currentApplyJob.jobId;

    try {
      let res = await Request.post('/business/job_apply', form);
      if (res.data.code !== 200) {
        throw new Error();
      }
      await Taro.showToast({
        title: '投递成功！',
        icon: "success",
        duration: 1000
      });
      await this.checkApplyStatus();
    } catch (e) {
      await Taro.showToast({
        title: '提交失败请重试',
        icon: "error",
        duration: 1000
      })
    } finally {
      this.setState({
        loading: false
      });
    }
  }

  async submitForm() {
    if (this.state.loading) {
      return;
    }
    this.state.loading = true;
    this.setState({
      loading: true
    })
    let { form } = this.state;
    if (!this.validateForm(form)) {
      this.setState({
        loading: false
      });
      return;
    }
    form.wxUserName = global.userInfo.userName;
    form.masterId = global.userInfo.userId;
    form.masterType = Number(global.userInfo.companyAuthStatus === '2');
    form.companyId = global.userInfo.bindingCompanyId;
    form.companyName = global.userInfo.bindingCompanyName;
    form.status = '1';
    try {
      let res = await Request.post('/business/jobs', form);
      console.log(res)
      if (res.data.code !== 200) {
        throw new Error();
      }
      await Taro.navigateBack();
      await Taro.showToast({
        title: '提交成功！',
        icon: "success",
        duration: 1000
      });
      Event.emit('updateJobs');
    } catch (e) {
      await Taro.showToast({
        title: '提交失败请重试',
        icon: "error",
        duration: 1000
      })
    } finally {
      this.setState({
        loading: false
      });
    }

  }

  async checkApplyStatus() {
    try {
      let res = await Request.get('/wx/checkHasApply?jobId=' + global.currentApplyJob.jobId + '&userId=' + global.userInfo.userId);
      if (res.data.code !== 200) {
        throw new Error();
      }
      this.setState({
        isApply: res.data.data
      })
    } catch (e) {
      console.log('检查投递状态失败')
    }
  }


  render () {
    let { form, loading, editable, isApply} = this.state;

    let msgComponent = <Text className='msg_container color-blue'>{global.isApplyJob ? '请点击投递进行职位申请' : '填入以下信息进行岗位发布'}</Text>;


    return (
      <View className='binding_container'>
        <View className='auth_msg_container'>
          {isApply ? <Text className='msg_container color-blue'>投递完成，请您耐心等待回复</Text> : msgComponent}
        </View>
        <View className='input_item'>
          <Text className='required'>岗位名称</Text>
          <Input disabled={!editable} value={form.name} onInput={(e) => {this.setState({form: {...form, name: e.detail.value}})}} type='text' placeholder='请输入岗位名称'/>
        </View>
        <View className='input_item'>
          <Text className='required'>联系方式</Text>
          <Input disabled={!editable} value={form.phone} onInput={(e) => {this.setState({form: {...form, phone: e.detail.value}})}} type='text' placeholder='请输入职位联系方式'/>
        </View>
        <View className='input_item'>
          <Text className='required'>薪资待遇</Text>
          <Input disabled={!editable} value={form.salary} onInput={(e) => {this.setState({form: {...form, salary: e.detail.value}})}} type='text' placeholder='5000~10000元、面议'/>
        </View>
        <View className='input_item'>
          <Text className='required'>经验要求</Text>
          <Input disabled={!editable} value={form.experience} onInput={(e) => {this.setState({form: {...form, experience: e.detail.value}})}} type='text' placeholder='1~3年、3~5年、不限'/>
        </View>
        <View className='input_item'>
          <Text className='required'>学历要求</Text>
          <Input disabled={!editable} value={form.education} onInput={(e) => {this.setState({form: {...form, education: e.detail.value}})}} type='text' placeholder='中专、高中、大专、本科、不限'/>
        </View>
        <View className='input_item'>
          <Text className='required'>职位要求</Text>
          <Textarea disabled={!editable} value={form.requirement} onInput={(e) => {this.setState({form: {...form, requirement: e.detail.value}})}} type='text' placeholder='请输入职位要求'/>
        </View>
        <View className='input_item'>
          <Text className='required'>职位描述</Text>
          <Textarea disabled={!editable} value={form.des} onInput={(e) => {this.setState({form: {...form, des: e.detail.value}})}} type='text' placeholder='请输入职位描述'/>
        </View>
        {
          editable && <Button loading={loading} className='submit_btn' type='primary' onClick={this.submitForm}>发布岗位</Button>
        }
        {
          editable && <View className='tips'>
            <Text className='iconfont icon-tanhao size40'/>
            <Text className='size28'> 请确保该信息真实有效，我们将随时进行核实</Text>
          </View>
        }
        {
          global.isApplyJob && <Button disabled={isApply} loading={loading} className='submit_btn' type='primary' onClick={this.applyJob}>{isApply ? '已投递' : '投递该岗位'}</Button>
        }
        {
          global.isApplyJob && <View className='tips'>
            <Text className='iconfont icon-tanhao size40'/>
            <Text className='size28'> 投递之后招聘方将收到您的联系方式，请您耐心等待招聘方回复</Text>
          </View>
        }
      </View>
    )
  }
}
